#include "hal_uart.h"
#include "driver/uart.h"
#include "freertos/queue.h"

#define BUF_SIZE 1024
static uart_rx_callback_t user_callback = NULL;

// 串口中断服务函数
static void IRAM_ATTR uart_isr(void* arg) {
    uart_device_t dev = (uart_device_t)arg;
    uint8_t buf[256];
    int len = uart_read_bytes(get_uart_port(dev), buf, sizeof(buf), 0);
    if (len > 0 && user_callback) {
        user_callback(dev, buf, len);
    }
}

void hal_uart_init() {
    for (int i = 0; i < UART_MAX; i++) {
        uart_device_t dev = (uart_device_t)i;
        int tx_pin, rx_pin;
        get_uart_pins(dev, &tx_pin, &rx_pin);

        uart_config_t cfg = {
            .baud_rate = (dev == UART_AIR780) ? 115200 : 9600,
            .data_bits = UART_DATA_8_BITS,
            .parity = UART_PARITY_DISABLE,
            .stop_bits = UART_STOP_BITS_1,
            .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
        };
        
        uart_param_config(get_uart_port(dev), &cfg);
        uart_set_pin(get_uart_port(dev), tx_pin, rx_pin, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE);
        uart_driver_install(get_uart_port(dev), BUF_SIZE, 0, 0, NULL, 0);
        uart_isr_register(get_uart_port(dev), uart_isr, (void*)dev, ESP_INTR_FLAG_IRAM, NULL);
    }
}

bool hal_uart_send(uart_device_t dev, const uint8_t* data, size_t len) {
    return uart_write_bytes(get_uart_port(dev), (const char*)data, len) == len;
}

void hal_uart_set_rx_callback(uart_rx_callback_t cb) {
    user_callback = cb;
}
